<?php
/**
 * Created by PhpStorm.
 * User: xionghao
 * Date: 2017/10/16
 * Time: 17:51
 */

namespace app\volunteer\controller;

use app\volunteer\model\VolunteerModel;
use cmf\controller\HomeBaseController;
use think\Controller;
use think\helper\Hash;

class RegisterController extends HomeBaseController
{

    public function index()
    {
        if (session('volunteer_login') == 1) {
            $this->redirect('volunteer/index/index');
        }else{
            return $this->fetch(':register');
        }
    }

    public function doRegister()
    {
        $volunteerModel = new VolunteerModel();
        $params = $this->request->param();
        if ($name = $this->request->param('username')) {
            $volunteer = $volunteerModel->where('username', $name)->find();
            if ($volunteer) {
                $this->error('账号已存在');
            }
        }
        if ($this->request->has('password')) {
            $params['password'] = Hash::make($params['password']);
        }


        $result = $volunteerModel->allowField(true)->save($params);
        if ($result) {
            $this->success('申请成功', cmf_url('volunteer/index/ok'));
        } else {
            $this->error('申请失败');
        }
    }

    public function photo()
    {

        $file = $this->request->file('file');
        $result = $file->validate([
            'ext' => 'jpg,jpeg,png',
            'size' => 1024 * 1024
        ])->move('.' . DS . 'upload' . DS . 'avatar' . DS);

        if ($result) {
            $avatarSaveName = str_replace('//', '/', str_replace('\\', '/', $result->getSaveName()));
            $avatar = 'avatar/' . $avatarSaveName;

            return json_encode([
                'code' => 1,
                "msg" => "上传成功",
                "data" => ['file' => $avatar],
                "url" => cmf_get_image_url($avatar)
            ]);
        } else {
            return json_encode([
                'code' => 0,
                "msg" => $file->getError(),
                "data" => "",
                "url" => ''
            ]);
        }
    }
}